﻿var simca = {
    settings: { domainUrl: "", loginUrl: "/User/Login" },
    messages: { error401: "Login required", error403: "Access deny" },
    showProcessingDialog: function () {
        //  simca.showDialog("ProcessingDialog");
        $('#processingDialogLayout').fadeIn(300);
        $('#OverLayLayout').addClass('DlgOverlay');
    },
    hideProcessingDialog: function (responseContext) {
        if (responseContext != null) {
            if (responseContext.status == 401) {
                simca.showMessage({ Type: "warning", Message: simca.messages.error401 });
                setTimeout(function () { simca.redirect(simca.settings.domainUrl + simca.settings.loginUrl); }, 3000);
            }
            if (responseContext.status == 403) {
                simca.showMessage({ Type: "error", Message: simca.messages.error403 });
            }
            if (responseContext.status == 909) {//thong bao loi cho client
                simca.showMessage(JSON.parse(responseContext.responseText))
            }

        }
        $('#processingDialogLayout').fadeOut(300);
        $('#OverLayLayout').removeClass('DlgOverlay');
    },
    showDialog: function (id) {
        $("#" + id).data("tWindow").center().open();
        simca.focusForm(id);
    },
    hideDialog: function (id) {
        simca.resetForm(id);
        $("#" + id).data("tWindow").close();
    },
    showMessage: function (msg) {
        var wpMsg = $(".simca-message.original").clone();
        $(wpMsg).removeClass("original");
        if (msg.Type == undefined) {
            var a = {};
            a.Type = 'error';
            a.Message = msg;
            msg = a;
        }
        if (msg) {
            $(wpMsg).find(".simca-message-content").text(msg.Message);

            if (msg.Type == 'success') {
                $(wpMsg).css({ "background-color": "#0c0" });
            }

            if (msg.Type == 'warning') {
                $(wpMsg).css({ "background-color": "#fc0" });
            }

            if (msg.Type == 'error') {
                $(wpMsg).css({ "background-color": "#f00" });
            }

            $("body").append(wpMsg);
            $(wpMsg).fadeIn(500);
            setTimeout(function () { $(wpMsg).fadeOut(500, function () { $(this).remove(); }) }, 3000);
        } else {
            alert(msg);
        }
    },
    getJsonObject: function (variable) {
        try {
            if ($.isPlainObject(variable)) {
                return variable;
            } else {
                jsonObj = eval('(' + variable + ')');
                return jsonObj;
            }
        } catch (e) {
            return null;
        }
    },
    serializeObject: function (id) {
        var a = $("#" + id + " :input").serializeArray();
        var o = {};
        $.each(a, function () {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    },
    post: function (url, data, callback) {
        $.ajax({
            url: url,
            type: "post",
            data: data,
            beforeSend: function () {
                simca.showProcessingDialog();
            },
            success: function (response) {
                simca.showMessage(response);

                if (callback != undefined && callback != null)
                    callback();
            },
            error: function () { },
            complete: function (responseContext) {
                simca.hideProcessingDialog(responseContext);
            }
        });
    },
    bindTo: function (data, containerId) {
        $.each(data, function (key, item) {
            var value = data[key];
            if ($.type(value) == 'string') {
                value = $.trim(value);

                var pos = value.indexOf("/Date(");
                if (value.indexOf("/Date(") >= 0) {
                    value = simca.convertStringDateToString(value);
                }
            }

            var item = $("#" + containerId).find('[name="' + key + '"]');

            if (item.attr("type") == "radio") {
                $.each(item, function (index, elm) {

                    if ($(elm).val() == value) {
                        setTimeout(function () { $(elm).attr("checked", "checked"); }, 300);
                    } else {
                        //setTimeout(function () { $(elm).removeAttr("checked"); }, 300);
                    }
                });
            } else if (item.attr("type") == "checkbox") {
                $.each(item, function (index, elm) {
                    if (value)
                        setTimeout(function () { $(elm).attr("checked", "checked"); }, 500);
                    else
                        $(elm).removeAttr("checked");
                });
            }
            else {
                $("#" + containerId).find('[name="' + key + '"]').val(value);
            }
        });
    },

    resetForm: function (containerId) {
        $("#" + containerId).find(":input").each(function () {
            var type = this.type;
            var tag = this.tagName.toLowerCase(); // normalize case

            if (type == 'text' || type == 'password' || tag == 'textarea')
                this.value = "";

            else if (type == 'checkbox' || type == 'radio')
                this.checked = false;

            else if (tag == 'select') {
                this.selectedIndex = 0;
            }
        });
        var inputs = $("#" + containerId).find(".input-validation-error");
        var msgs = $("#" + containerId).find(".field-validation-error");
        inputs.removeAttr("class");
        //truong hop dac biet Namta
        //nut button disabled

        $("#" + containerId + " .t-state-disabled").each(function () {
            $(this).attr("disabled", "");
        });

        $("#" + containerId + " button:disabled").each(function () {
            if (!$(this).hasClass(".t-state-disabled")) {
                $(this).addClass(".t-state-disabled");
            }
        });
        //disable duong dan
        $("#txtFilePath").attr("disabled", "");

        msgs.removeClass("field-validation-error");
        msgs.addClass("field-validation-valid");
        msgs.children().remove();
    },
    disableForm: function (containerId, IsDisable) {
        if (IsDisable) {
            $("#" + containerId).find(":input").attr("disabled", "disabled");
        } else {
            $("#" + containerId).find(":input").removeAttr("disabled");
        }
    },
    focusForm: function (formId) {
        setTimeout(function () {
            $("#" + formId).find(":input").not(":disabled,:hidden").eq(0).focus();
        }, 500);
    },
    convertDateToString: function (date) {
        if (date == null || date == undefined) return "";

        var day = date.getDate().toString();
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        month = month.toString();

        if (month.length == 1) {
            month = "0" + month;
        }

        if (day.length == 1) {
            day = "0" + day;
        }

        return day + "/" + month + "/" + year;
    },
    convertStringToDate: function (strDate) {
        var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;

        if (strDate == null || strDate == undefined || !re.test(strDate))
            return null;

        var adata = strDate.split('/');
        var mm = parseInt(adata[1], 10);
        var dd = parseInt(adata[0], 10);
        var yyyy = parseInt(adata[2], 10);

        var xdata = new Date(yyyy, mm - 1, dd);
        if ((xdata.getFullYear() == yyyy) && (xdata.getMonth() == mm - 1) && (xdata.getDate() == dd))
            return xdata;
        else
            return null;
    },
    convertStringDateToString: function (strDate) {
        var miliSeconds = parseInt(strDate.substring("/Date(".length, strDate.length - 2));
        var date = new Date(miliSeconds);
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        month = month.toString();
        if (month.length == 1) {
            month = "0" + month;
        }
        var day = date.getDate().toString();
        if (day.length == 1) {
            day = "0" + day;
        }
        var strDateTime = day + "/" + month + "/" + year;
        return strDateTime;
    },
    refreshGrid: function (gridId) {
        var grid = $('#' + gridId).data('tGrid');
        if (grid != null)
            grid.currentPage = 1;
        $("#" + gridId + " .t-refresh").trigger('click');
    },
    resetValidation: function (formId) {
        var form = $("#" + formId);

        //reset jQuery Validate's internals
        $("#" + formId).validate().resetForm();

        //reset unobtrusive validation summary, if it exists
        form.find("[data-valmsg-summary=true]")
            .removeClass("validation-summary-errors")
            .addClass("validation-summary-valid")
            .find("ul").empty();

        //reset unobtrusive field level, if it exists
        form.find("[data-valmsg-replace]")
            .removeClass("field-validation-error")
            .addClass("field-validation-valid")
            .empty();
    },
    validateForm: function (formId) {
        var form = $("#" + formId);

        //alert(simca.ValidateDateTime($(form)));
        if (!form.valid() || simca.ValidateDateTime($(form))) {
            var inputs = form.find(".input-validation-error");
            return false;
        }

        return true;
    },
    //validate DateTime Namta
    ValidateDateTime: function (form) {
        var ValidateDateTime;
        ValidateDateTime = false;
        $(".t-datepicker", form).each(function () {
            var inputDt = $(this).find("input");
            $(inputDt).focus();
            if ($(inputDt).not(":disabled") && $(inputDt).val() != "" && simca.convertStringToDate($(inputDt).val()) == null) {
                ValidateDateTime = true;
                if ($(this).next().hasClass('t-input valid t-state-error')) {
                    $(this).next().attr('class', 'field-validation-error');
                    var strValidate = '<span class="" htmlfor="' + $(this).next().attr('data-valmsg-for') + '" generated="true">';
                    strValidate = strValidate + 'Ngày tháng không đúng định dạng';
                    strValidate = strValidate + '</span>';
                    $(this).next().html(strValidate);
                }
            }
        });
        //return ValidateDateTime;
        return false;
    },
    ValidDate: function (form) {
        var result;
        result = true;
        $(".t-datepicker", form).each(function () {
            var inputDt = $(this).find("input");
            if ($(inputDt).not(":disabled") && $(inputDt).val() != "") {
                if (!simca.IsValidDate($(inputDt).val())) {
                    simca.showMessage({ Type: "error", Message: "Ngày nhập không đúng định dạng" })
                    $(inputDt).focus();
                    result = false;
                }
                var date = simca.convertStringToDate($(inputDt).val());
                if (date > new Date()) {
                    simca.showMessage({ Type: "error", Message: "Ngày nhập nhỏ hơn ngày hiện tại" })
                    setTimeout(function () { $(inputDt).focus(); }, 300);
                    result = false;
                }
            }
        });
        return result;
    },
    IsValidDate: function (value) {
        if (value == null || $.trim(value) == "") {
            return true;
        }
        var check = false;
        var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
        if (re.test(value)) {
            var adata = value.split('/');
            var mm = parseInt(adata[1], 10);
            var dd = parseInt(adata[0], 10);
            var yyyy = parseInt(adata[2], 10);
            var xdata = new Date(yyyy, mm - 1, dd);
            if ((xdata.getFullYear() == yyyy) && (xdata.getMonth() == mm - 1) && (xdata.getDate() == dd))
                check = true;
            else
                check = false;
        } else
            check = false;
        return check;
    },
    /**
   * Hàm không cho phép nhập kí tự đặc biệt
   **/
    checkchar: function (e) {
        if ((e.which < 48 || (e.which > 57 && e.which < 65) || (e.which > 123 && e.which < 127) || (e.which > 91 && e.which < 96)) && e.which != 8 && e.which != 44 && e.which != 0) {
            return false;
        }
        else {
            return true;
        }

    },
    redirect: function (url) {
        window.location = url;
    },
    /**
     * Hàm chỉ cho phép nhập số 
    **/
    requestNumber: function (e) {
        if (window.event) { // IE
            var charCode = window.event.keyCode;
        } else if (e.which) { // Safari 4, Firefox 3.0.4
            var charCode = e.which
        }

        if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;
        return true;
    },
    /**
     * Hàm chỉ cho phép nhập số và dấu (.)
    **/
    requestDecimal: function (e) {
        if (window.event) { // IE
            var charCode = window.event.keyCode;
        } else if (e.which) { // Safari 4, Firefox 3.0.4
            var charCode = e.which
        }
        if (charCode == 44) {
            return true;
        }
        if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;
        return true;
    },

    addMoveButtonEvent: function (GridID) {
        $("input[type=text]", GridID).focus(function (event) {
            $("td", GridID).removeClass("FocusTD");
            var td = $(this).parents(GridID + " td").first();
            $(td).addClass("FocusTD");
        });

        $("td", GridID).click(function (event) {
            var input = $(this).children("input[type=text]").first();
            if (simca.IsEditable(input)) {
                event.stopPropagation();
                input.focus(function () {
                    this.select();
                }).focus();
            }
        });

        $("input[type=text]", GridID).unbind("keydown").keydown(function (event) {
            event.stopPropagation();
            var tr = $(this).parents(GridID + " tr").last();
            var index = $("input[type=text]", tr).index(this);
            var max = $("input[type=text]", tr).length;
            switch (event.keyCode.toString()) {
                //case "13":
                case "40": //Move Down
                    var ntr = tr;
                    var next = true;
                    var input = null;
                    while (next) {
                        ntr = ntr.next(GridID + " tr");
                        if (ntr.length > 0) {
                            input = $("input[type=text]:eq(" + index + ")", ntr);
                            next = !simca.IsEditable(input);
                        } else {
                            next = false;
                        }
                    }
                    if (input != null && simca.IsEditable(input)) {
                        input.focus(function () {
                            this.select();
                        }).focus();
                    }
                    return false;
                case "38": //Move Up
                    var ntr = tr;
                    var next = true;
                    var input = null;
                    while (next) {
                        ntr = ntr.prev(GridID + " tr");
                        if (ntr.length > 0) {
                            input = $("input[type=text]:eq(" + index + ")", ntr);
                            next = !simca.IsEditable(input);

                        } else {
                            next = false;
                        }
                    }
                    if (input != null && simca.IsEditable(input)) {
                        input.focus(function () {
                            this.select();
                        }).focus();
                    }
                    return false;
                case "39": //Move Right
                    var idx = index;
                    var next = true;
                    var input = null;
                    while (next) {
                        idx++;
                        if (idx >= 0 && idx < max) {
                            input = $("input[type=text]:eq(" + idx + ")", tr);
                            next = !simca.IsEditable(input);
                        } else {
                            next = false;
                        }
                    }
                    if (input != null && simca.IsEditable(input)) {
                        input.focus(function () {
                            this.select();
                        }).focus();
                    }

                    return false;
                case "37": //Move Left
                    var idx = index;
                    var next = true;
                    var input = null;
                    while (next) {
                        idx--;
                        if (idx >= 0 && idx < max) {
                            input = $("input[type=text]:eq(" + idx + ")", tr);
                            next = !simca.IsEditable(input);
                        } else {
                            next = false;
                        }
                    }
                    if (input != null && simca.IsEditable(input)) {
                        input.focus(function () {
                            this.select();
                        }).focus();
                    }
                    return false;
            }
        });
    },

    IsEditable: function (obj) {
        var input = $(obj);
        if (input.length > 0 && !input.is(":hidden") && input.css('display') != 'none'
            && !input.is(":disabled") && !input.is("[readonly]")) {
            return true;
        } else {
            return false;
        }
    }
};